/*
*   @Author: 1296
*   @Date: 2025-03-17
*   @Description: 登录与注册页（重写）
*/

<template>
  <div class="page-container">
    <img src="@/assets/logo.png" alt="Logo" class="logo" />
    <img src="@/assets/title.png" alt="Title" class="title" />
    <div class="carousel">
      <carousel-component />
    </div>
    <div class="auth-container">
      <!-- 模态框部分保持不变 -->
      <div v-if="registerSuccess" class="modal-mask">
        <div class="success-modal">
          <div class="success-icon">✔️</div>
          <div class="success-title">{{ $t('login.regSuccessTitle') }}</div>
          <div class="success-content">{{ $t('login.regSuccessContent') }}</div>
          <button class="success-button" @click="closeModalRegister">{{ $t('common.confirm') }}</button>
        </div>
      </div>
      <div v-if="loginSuccess" class="modal-mask">
        <div class="success-modal">
          <div class="success-icon">✔️</div>
          <div class="success-title">{{ $t('login.logSuccessTitle') }}</div>
        </div>
      </div>

      <!-- 表单部分 -->
      <div class="auth-toggle">
        <button :class="{ active: isLoginActive }" @click="toggleAuth('login')">
          {{ $t('login.loginChoice') }}
        </button>
        <button :class="{ active: !isLoginActive }" @click="toggleAuth('register')">
          {{ $t('login.registerChoice') }}
        </button>
      </div>

      <div class="auth-form">
        <form @submit.prevent="handleSubmit">
          <template v-if="isLoginActive">
            <input
                type="text"
                v-model="phone"
                :placeholder="$t('login.phone')"
                class="input-field"
            />
            <input
                type="password"
                v-model="password"
                :placeholder="$t('login.password')"
                class="input-field"
            />
          </template>

          <template v-else>
            <div class="form-row">
              <input
                  type="text"
                  v-model="username"
                  :placeholder="$t('login.username')"
                  class="input-field"
              />
              <input
                  type="text"
                  v-model="jobCode"
                  :placeholder="$t('login.jobCode')"
                  class="input-field"
              />
            </div>
            <div class="form-row">
              <input
                  type="text"
                  v-model="phone"
                  :placeholder="$t('login.phone')"
                  class="input-field"
              />
              <input
                  type="text"
                  v-model="email"
                  :placeholder="$t('login.email')"
                  class="input-field"
              />
            </div>
            <div class="form-row">
              <input
                  type="password"
                  v-model="password"
                  :placeholder="$t('login.setPassword')"
                  class="input-field"
              />
              <input
                  type="password"
                  v-model="confirmPassword"
                  :placeholder="$t('login.confirmPassword')"
                  class="input-field"
              />
            </div>
            <div class="role-selection">
              <div class="select-role-label">{{ $t('login.selectRole') }}</div>
              <el-radio-group v-model="jobPosition">
                <el-row>
                  <el-col :span="12">
                    <el-radio label="1">{{ $t('roles.teacher') }}</el-radio>
                  </el-col>
                  <el-col :span="12">
                    <el-radio label="0">{{ $t('roles.student') }}</el-radio>
                  </el-col>
                </el-row>
              </el-radio-group>
            </div>
          </template>
          <button type="submit" class="submit-button">
            {{ isLoginActive ? $t('login.loginNow') : $t('login.registerNow') }}
          </button>
          <div class="forgot-password" v-if="isLoginActive">
            <router-link to="/forgotPassword">{{ $t('login.forgotPassword') }}</router-link>
          </div>
        </form>
        <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>
      </div>

      <a href="/" class="continue-link">{{ $t('login.continueWithout') }}</a>

    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import CarouselComponent from "@/components/Carousel.vue";
import store from "@/store";
import {useI18n} from "vue-i18n";
const { t } = useI18n()

const router = useRouter();
const api = axios.create({
  baseURL: store.getters.getBaseURL
});

const isLoginActive = ref(true);
const username = ref('');
const phone = ref('');
const password = ref('');
const confirmPassword = ref('');
const email = ref('');
const errorMessage = ref('');
const jobPosition = ref('');
const jobCode = ref('')
const registerSuccess = ref(false);
const loginSuccess = ref(false);

const closeModalRegister = () => {
  registerSuccess.value = false;
  router.go(0);
};

const closeModalLogin = () => {
  loginSuccess.value = false;
}

const validatePhone = (phone) => {
  return /^1[3-9]\d{9}$/.test(phone);
};

const validateForm = () => {
  if (!isLoginActive.value) {
    if (!jobPosition.value) {
      errorMessage.value = t('login.errors.selectRole');
      return false;
    }
    if (username.value.trim().length < 1) {
      errorMessage.value = t('login.errors.usernameLength');
      return false;
    }
    if (!validatePhone(phone.value)) {
      errorMessage.value = t('login.errors.phoneFormat');
      return false;
    }
    if (!/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(email.value)) {
      errorMessage.value = t("login.errors.emailFormat");
      return false;
    }
    if (email.value.trim() === '') {
      errorMessage.value = t('login.errors.emailRequired');
      return false;
    }
    if (!jobCode.value) {
      errorMessage.value = t('login.errors.jobCodeRequired')
    }
  } else {
    if (phone.value.trim() === '') {
      errorMessage.value = t('login.errors.phoneRequired');
      return false;
    }
  }
  if (password.value.length < 6) {
    errorMessage.value = t('login.errors.passwordLength');
    return false;
  }
  return true;
};

const toggleAuth = (type) => {
  isLoginActive.value = (type === 'login');
  jobPosition.value = '';
  username.value = '';
  phone.value = '';
  password.value = '';
  confirmPassword.value = '';
  email.value = '';
  errorMessage.value = '';
  jobCode.value = '';
};

const handleSubmit = async () => {
  errorMessage.value = '';
  if (!validateForm()) return;
  if (!isLoginActive.value && password.value !== confirmPassword.value) {
    errorMessage.value = t('login.errors.passwordMismatch');
    return;
  }
//登录注册请求体
  try {
    if (isLoginActive.value) {
      try {
        const response = await api.post('/user/login', {
          phone: phone.value,
          password: password.value
        });
        sessionStorage.setItem('id', response.data.data.id);
        sessionStorage.setItem('userToken', response.data.data.token);
        sessionStorage.setItem('username', response.data.data.username);
        sessionStorage.setItem('role', response.data.data.role);
        sessionStorage.setItem('phone', response.data.data.phone);
        sessionStorage.setItem('email', response.data.data.email);
        sessionStorage.setItem('avatar', response.data.data.avatar);
        sessionStorage.setItem('gender', response.data.data.gender);
        sessionStorage.setItem('institute', response.data.data.institute);
        sessionStorage.setItem('major', response.data.data.major);
        sessionStorage.setItem('className', response.data.data.className);
        sessionStorage.setItem('jobCode', response.data.data.jobCode);
        // console.log("Current sessionStorage:", JSON.stringify(sessionStorage));
        store.commit('SET_USER', {
          id: response.data.data.id,
          token: response.data.data.token,
          username: response.data.data.username,
          role: response.data.data.role,
          phone: response.data.data.phone,
          email: response.data.data.email,
          avatar: response.data.data.avatar,
          gender: response.data.data.gender,
          institute: response.data.data.institute,
          major: response.data.data.major,
          className: response.data.data.className,
          jobCode: response.data.data.jobCode
        });
        loginSuccess.value = true;
        setTimeout(async () => {
          closeModalLogin();
          await router.push(`/${response.data.data.jobCode}/dashboard`);
        }, 1000);
      } catch (error) {
        errorMessage.value = error.response?.data?.info || t('login.errors.loginFailed');
      }
    } else {
      let checkResponse;
      try {
        checkResponse = await api.post('/user/checkAccount', {
          username: username.value,
          phone: phone.value,
          email: email.value
        });
      } catch (error) {
        errorMessage.value = error.response?.data?.info || t('common.requestFailed');
      }
      console.log(checkResponse.data.code);
      // 目前先这样写
      if (checkResponse.data.code === 600) {
        errorMessage.value = t('userExists')
      }

      if (checkResponse.data.code === 200) {
        await api.post('/user/register', {
          username: username.value,
          phone: phone.value,
          email: email.value,
          role: jobPosition.value,
          jobCode: jobCode.value,
          password: password.value,
          rePassword: confirmPassword.value
        });

        registerSuccess.value = true;
        setTimeout(() => {
          closeModalRegister();
        }, 1000);

        // 清空表单
        username.value = '';
        phone.value = '';
        email.value = '';
        jobPosition.value = '';
        jobCode.value = '';
        password.value = '';
        confirmPassword.value = '';
      }
    }
  } catch (error) {
    errorMessage.value = error.response?.data?.info || t('common.requestFailed');
  }
};

// 拦截器
api.interceptors.request.use(config => {
  const token = sessionStorage.getItem('userToken');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

api.interceptors.response.use(
    response => response,
    error => {
      if (error.response?.status === 401) {
        router.push('/loginAndRegister');
      }
      return Promise.reject(error);
    }
);
</script>

<style scoped>
.page-container {
  position: relative;
  width: 100%;
  height: 100vh;
}

.carousel {
  position: absolute;
  left: calc(77 / 1920 * 100vw);
  top: calc(300 / 1080 * 100vh);
}

.title {
  position: absolute;
  left: calc(1073 / 1920 * 100vw);
  top: calc(200 / 1080 * 100vh);
  width: calc(344 / 1920 * 100vw);
  height: calc(100 / 1080 * 100vh);
}

.logo {
  position: absolute;
  left: calc(1516 / 1920 * 100vw);
  top: calc(157 / 1080 * 100vh);
  width: calc(135 / 1920 * 100vw);
  height: calc(128 / 1080 * 100vh);
}

.auth-container {
  position: absolute;
  left: calc(1073 / 1920 * 100vw);
  top: calc(300 / 1080 * 100vh);
  width: calc(680 / 1920 * 100vw);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.auth-toggle {
  display: flex;
  width: 100%;
  justify-content: space-between;
}

.auth-toggle button {
  width: calc(340 / 1920 * 100vw);
  height: calc(100 / 1080 * 100vh);
  font-size: calc(28 / 1920 * 100vw);
  color: #ABABAB;
  border: none;
  border-bottom: calc(1 / 1920 * 100vw) solid #BBBBBB;
  background: transparent;
  cursor: pointer;
  transition: all 0.3s;
}

.auth-toggle button.active {
  color: #101010;
  border-bottom: calc(3 / 1920 * 100vw) solid #008FEE;
}

.auth-form {
  width: 100%;
  margin-top: calc(20 / 1080 * 100vh);
}

.input-field {
  width: calc(640 / 1920 * 100vw);
  height: calc(80 / 1080 * 100vh);
  padding: 0 calc(20 / 1920 * 100vw);
  font-size: calc(24 / 1920 * 100vw);
  color: #888888;
  border: calc(1 / 1920 * 100vw) solid #BBBBBB;
  border-radius: calc(100 / 1920 * 100vw);
  outline: none;
  transition: all 0.3s;
  margin-bottom: calc(60 / 1080 * 100vh);
}

.input-field:not(:placeholder-shown) {
  color: #101010;
}

.form-row {
  display: flex;
  gap: calc(30 / 1920 * 100vw);
  width: 100%;
  margin-bottom: calc(30 / 1080 * 100vh);
}

.form-row .input-field {
  flex: 1;
  width: 90%;
  margin-bottom: 0;
}

.submit-button {
  width: 100%;
  height: calc(80 / 1080 * 100vh);
  font-size: calc(28 / 1920 * 100vw);
  color: #FFFFFF;
  background-color: #008FEE;
  border: none;
  border-radius: calc(100 / 1920 * 100vw);
  cursor: pointer;
  transition: background-color 0.3s;
  margin-top: calc(10 / 1080 * 100vh);
  margin-bottom: calc(20 / 1080 * 100vh);
}

.submit-button:hover {
  background-color: #007ACC;
}

.continue-link {
  margin-top: calc(20 / 1080 * 100vh);
  font-size: calc(20 / 1920 * 100vw);
  color: #ABABAB;
  text-decoration: underline;
  cursor: pointer;
}

.error-message {
  color: #ff4d4f;
  font-size: calc(24 / 1920 * 100vw);
  margin-top: calc(20 / 1080 * 100vh);
  text-align: center;
  height: calc(30 / 1080 * 100vh);
}

.input-field:focus {
  border-color: #008FEE;
  box-shadow: 0 0 0 2px rgba(0, 143, 238, 0.2);
}

.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(5px);
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.success-modal {
  background: #ffffff;
  padding: 30px 50px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  text-align: center;
  color: #101010;
  font-size: calc(28 / 1920 * 100vw);
  z-index: 1000;
  animation: scaleIn 0.3s ease-in-out;
  transform-origin: center;
}

.success-icon {
  font-size: calc(48 / 1920 * 100vw);
  color: #4caf50;
  margin-bottom: 20px;
}

.success-title {
  font-size: calc(32 / 1920 * 100vw);
  font-weight: bold;
  margin-bottom: 10px;
}

.success-content {
  font-size: calc(24 / 1920 * 100vw);
  color: #666666;
}

.success-button {
  margin-top: 20px;
  padding: 10px 20px;
  font-size: calc(24 / 1920 * 100vw);
  color: #ffffff;
  background-color: #4caf50;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.success-button:hover {
  background-color: #45a049;
}

@keyframes scaleIn {
  0% {
    transform: scale(0.8);
    opacity: 0;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

@keyframes fadeOut {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

.forgot-password {
  text-align: center;
  width: 100%;
  margin-bottom: calc(10 / 1080 * 100vh);
}

.forgot-password a {
  color: #008FEE;
  font-size: calc(24 / 1920 * 100vw);
  text-decoration: underline;
  transition: opacity 0.3s;
}

.forgot-password a:hover {
  opacity: 0.8;
}

.select-role-label {
  font-size: 12px;
  color: #888888;
  width: calc(120 / 1920 * 100vw);
  margin-left: 1.2vw;
}

.role-selection {
  flex: 1;
  display: flex;
  align-items: center;
  width: 100%;
  margin-bottom: 2vh;
}

:deep(.el-radio-group) {
  display: flex;
  width: 100%;
}

:deep(.el-row) {
  width: 100%;
}

:deep(.el-col) {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 50%;
}
</style>